package com.core.gwt.place.client;

import com.google.gwt.place.shared.Place;

/**
 * An abstract base class for {@link Place} implementations that serialize their
 * state into a URL token with the help of a {@link PlaceToken}.<br>
 * <br>
 * It provides a constructor which accepts a URL token as an argument - to
 * initialize a place from a token - and a {@link #toToken} method - to generate
 * a token representing the state of the place.<br>
 * <br>
 * Classes extending <code>TokenizablePlace</code> will override the
 * {@link #saveState} method to store their state into the provided
 * {@link PlaceToken} object and the {@link #loadState} method to load their
 * state from the provided {@link PlaceToken} object.
 * 

 */
public abstract class TokenizablePlace extends Place {
	public TokenizablePlace() {
		// Load the default state (from a blank token)
		final PlaceToken blank = new PlaceToken();
		loadState(blank);
	}

	/**
	 * Initializes a {@link TokenizablePlace} from a URL token.
	 */
	public TokenizablePlace(final String token) {
		// Parse the token and load the state from it
		final PlaceToken parser = new PlaceToken(token);
		loadState(parser);
	}

	/**
	 * Override to load the state of your place object from a URL token parsed
	 * into a {@link PlaceToken} object.
	 */
	protected void loadState(final PlaceToken token) {

	}

	/**
	 * Override to save the state of your place object into a URL token to be
	 * built from a {@link PlaceToken} object.
	 */
	protected void saveState(final PlaceToken token) {

	}

	/**
	 * Returns a URL token representing the state of the place object.
	 */
	public String toToken() {
		// Save the state into a token
		final PlaceToken builder = new PlaceToken();
		saveState(builder);
		return builder.toString();
	}
}
